package com.niuwa.p2p.service.impl.redenvelope;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.niuwa.p2p.core.mvc.entity.JsonResult;
import com.niuwa.p2p.core.mvc.entity.PageBean;
import com.niuwa.p2p.core.utils.DateUtil;
import com.niuwa.p2p.core.utils.DictConstant;
import com.niuwa.p2p.core.utils.StringUtil;
import com.niuwa.p2p.dao.redenvelope.RedEnvelopeRuleDao;
import com.niuwa.p2p.dao.redenvelope.RedRangeDao;
import com.niuwa.p2p.entity.PageQuery;
import com.niuwa.p2p.entity.redenvelope.RedEnvelopeRule;
import com.niuwa.p2p.entity.redenvelope.RedRange;
import com.niuwa.p2p.service.redenvelope.IRedEnvelopeRuleService;
import com.niuwa.p2p.service.sequence.ISequenceService;
import com.niuwa.p2p.vo.redenvelope.RedEnvelopeRuleVo;

@Service
public class RedEnvelopeRuleServiceImpl implements IRedEnvelopeRuleService{
	
	@Autowired
	private RedEnvelopeRuleDao envelopeRuleDao;
	
	@Autowired
	private RedRangeDao rangeDao;
	
	@Autowired
	private ISequenceService sequenceService;

	@Override
	public JsonResult addRedEnvelopeRule(RedEnvelopeRuleVo ruleVo) {
		JsonResult jsonResult = new JsonResult(false,"操作失败");
		int result = 0;//影响行数
		if(ruleVo != null){
			RedEnvelopeRule rule = ruleVo.getEnvelopeRule();
			if(rule != null){
				//查询规则名称是否重复
				result = envelopeRuleDao.selectRedEnvelopeRuleByRuleName(rule.getRuleName());
				if(result == 0){
					try {
						//当期时间
						Date date = new Date();
						//生效时间
						Date startDate = rule.getStartDate();
						rule.setCreateTime(date);
						//判断 有效期类型
						if("NODAY".equals(rule.getDayType())){
							rule.setValidTermType(rule.getValidTermType());
							rule.setValidTermDays(null);
						}else if("DAYS".equals(rule.getDayType())){
							rule.setValidTermType(rule.getDayType());
							rule.setValidTermDays(rule.getValidTermDays());
						}
						//金额为区间
						if("AREA".equals(rule.getAmtType())){
							rule.setAmount(null);
							rule.setAmountPercent(null);
							if(ruleVo.getEndAmount() == null || ruleVo.getStartAmount() == null || ruleVo.getRedAmount() == null){
								return jsonResult=new JsonResult(false,"金额为区间时，至少必须存在一个区间!");
							}
						}
						//金额为固定值
						if("FIX".equals(rule.getAmtType())){
							rule.setAmountPercent(null);
							ruleVo.setStartAmount(null);
							ruleVo.setEndAmount(null);
							ruleVo.setRedAmount(null);
						}
						//金额为比例
						if("PER".equals(rule.getAmtType())){
							rule.setAmount(null);
							ruleVo.setStartAmount(null);
							ruleVo.setEndAmount(null);
							ruleVo.setRedAmount(null);
						}
						//判断触发动作是否为投资
						if(!"INVEST".equals(rule.getTriggerAction())){
							rule.setOverAmount(null);
						}
						//规则状态
						if(DateUtil.isAfter(startDate, date)){
							rule.setStatus(DictConstant.redRuleStatus.WAIT_VALID.getCode());
						}else{
							rule.setStatus(DictConstant.redRuleStatus.HAD_VALID.getCode());
						}
						//规则编号
						String ruleNo = sequenceService.getCompleteSequenceBySeqKey("HBGZ");
						rule.setRuleNo(ruleNo);
						rule.setDelFlag(DictConstant.FlagStatus.N.toString());
						//添加规则
						result = envelopeRuleDao.insert(ruleVo.getEnvelopeRule());
						if(result > 0){
							if(ruleVo.getEndAmount() == null || ruleVo.getStartAmount() == null || ruleVo.getRedAmount() == null){
								jsonResult=new JsonResult(true,"添加成功!");
							}else{
								if(ruleVo.getEndAmount().length != 0 || ruleVo.getStartAmount().length != 0 || ruleVo.getRedAmount().length != 0){
									//添加规则红包区间
									jsonResult = addRange(ruleNo, ruleVo);
								}else{
									jsonResult=new JsonResult(true,"添加成功!");
								}
							}
						}else{
							jsonResult=new JsonResult(false,"添加规则失败!");
						}
					} catch (Exception e) {
						jsonResult=new JsonResult(false,"操作异常!");
					}
				}else{
					jsonResult=new JsonResult(false,"存在该规则名称!");
				}
			}else{
				jsonResult=new JsonResult(false,"操作异常!");
			}
		}else{
			jsonResult=new JsonResult(false,"操作异常!");
		}
		return jsonResult;
	}
	
	/**
	 * 新增区间值
	 * 
	 * @param tempId
	 * @param form
	 */
	private JsonResult addRange(String ruleNo, RedEnvelopeRuleVo ruleVo) {
		JsonResult jsonResult = new JsonResult(false,"操作失败");
		int result = 0;
		// 金额开始集合
		String[] startAcounts = ruleVo.getStartAmount();
		// 金额开始集合长度
		int startAcountLen = startAcounts.length;
		// 金额截止集合
		String[] endAcounts = ruleVo.getEndAmount();
		// 金额截止集合长度
		int endCountLen = endAcounts.length;
		// 红包金额	
		String[] redAcounts = ruleVo.getRedAmount();
		// 红包金额长度
		int redAcountLen = redAcounts.length;
		//存放金额区间数据
		List<RedRange> list = new ArrayList<RedRange>();
		
		//先判断第一个区间和最后一个区间的正确性
		//第一个区间的开始金额
		String firstStartAmount = startAcounts[0];
		//第一个区间的结束金额
		String firstEndAmount = endAcounts[0];
		//第一个区间的红包金额
		String firstRedAcount = redAcounts[0];
		//最后一个区间的开始金额
		String lastStartAmount = startAcounts[startAcountLen - 1];
		//最后一个区间的结束金额
		String lastEndAmount = endAcounts[endCountLen - 1];
		//最后一个区间的红包金额
		String lastRedAcount = redAcounts[redAcountLen - 1];
		BigDecimal maxAmount = new BigDecimal(9999999999L);
		/**********************第一个区间***************************/
		RedRange range = new RedRange();
		if(StringUtil.isEmpty(firstEndAmount)){
			return jsonResult = new JsonResult(false,"第1个区间的结束金额为空");
		}
		String firstStartAmount1 = null;//第一个区间的开始金额
		if(StringUtil.isEmpty(firstStartAmount)){
			firstStartAmount1 = "0";
		}else{
			firstStartAmount1 = firstStartAmount;
		}
		BigDecimal firstStartAmount2 = new BigDecimal(firstStartAmount1);
		BigDecimal firstEndAmount1 = new BigDecimal(firstEndAmount);
		if(firstStartAmount2.compareTo(firstEndAmount1) == 1){
			return jsonResult = new JsonResult(false,"第1个区间开始金额不能大于结束金额");
		}
		range.setStartAmount(firstStartAmount2);
		range.setEndAmount(firstEndAmount1);
		if(StringUtil.isEmpty(firstRedAcount)){
			return jsonResult = new JsonResult(false,"第1个区间的红包金额为空");
		}else{
			BigDecimal firstRedAcount1 = new BigDecimal(firstRedAcount);
			range.setRedAmount(firstRedAcount1);
		}
		range.setRuleNo(ruleNo);
		list.add(range);
		/**********************第一个区间***************************/
		if(startAcountLen != 1 || endCountLen != 1 || redAcountLen != 1){
			if(startAcountLen > 2 && endCountLen > 2 && redAcountLen > 2){
				/***************判断除了首个区间和最后一个区间其他区间的正确性*******************/
				for (int i = 1; i < startAcounts.length-1; i++) {
					RedRange range1 = new RedRange();
					range1.setRuleNo(ruleNo);
					if(null != startAcounts[i] && !"".equals(startAcounts[i]) && null != endAcounts[i] && !"".equals(endAcounts[i])){
						BigDecimal startAmount = new BigDecimal(startAcounts[i]);
						BigDecimal endAcount = new BigDecimal(endAcounts[i]);
						BigDecimal firstEndAmount2 = new BigDecimal(endAcounts[i - 1]);
						BigDecimal startBeforeAmount = new BigDecimal(Integer.valueOf(endAcounts[i - 1]) + 1);
						if(startAmount.compareTo(endAcount) == 1){
							return jsonResult = new JsonResult(false,"第"+(i+1)+"个区间开始金额不能大于结束金额");
						}
						if(maxAmount.compareTo(firstEndAmount2) == 0){
							return jsonResult = new JsonResult(false,"第"+(i)+"个区间的结束金额已为最大值");
						}
						if(startAmount.compareTo(firstEndAmount2) == -1){
							return jsonResult = new JsonResult(false,"第"+(i+1)+"个区间开始金额必须大于上个区间的结束金额");
						}
						if(startAmount.compareTo(startBeforeAmount) != 0){
							return jsonResult = new JsonResult(false,"第"+(i+1)+"个区间开始金额必须为上个区间的结束金额加1");
						}
							/*if(Integer.valueOf(startAcounts[i]) != (Integer.valueOf(firstEndAmount) + 1)){
								return jsonResult = new JsonResult(false,"第"+(i+1)+"个区间开始金额必须为上个区间的结束金额加1");
							}*/
						/*if(Integer.valueOf(startAcounts[i]) < Integer.valueOf(firstEndAmount)){
							return jsonResult = new JsonResult(false,"第"+(i+1)+"个区间开始金额必须大于上个区间的结束金额");
						}*/
						range1.setStartAmount(startAmount);
						range1.setEndAmount(endAcount);
					}else{
						return jsonResult = new JsonResult(false,"第"+(i+1)+"个区间填写不完整");
					}
					if (null != redAcounts[i] && !"".equals(redAcounts[i])) {
						BigDecimal redAcount=new BigDecimal(redAcounts[i]);
						range1.setRedAmount(redAcount);
					}else{
						return jsonResult = new JsonResult(false,"第"+(i+1)+"个区间红包金额为空");
					}
					list.add(range1);
				}
				/**************判断除了首个区间和最后一个区间其他区间的正确性****************/
			}
			/**************最后区间的上个区间的结束金额的值****************/
			String endBeforeAmount = null;
			if(startAcountLen == 2 && endCountLen == 2 && redAcountLen == 2){
				endBeforeAmount = firstEndAmount;
			}else{
				endBeforeAmount = endAcounts[endCountLen - 2];
			}
			/**************最后区间的上个区间的结束金额的值****************/
			/**********************最后区间***************************/
			RedRange range2 = new RedRange();
			if(StringUtil.isEmpty(lastStartAmount)){
				return jsonResult = new JsonResult(false,"最后1个区间的开始金额为空");
			}
			BigDecimal lastStartAmount1 = new BigDecimal(lastStartAmount);
			BigDecimal endBeforeAmount1 = new BigDecimal(endBeforeAmount);
			if(maxAmount.compareTo(endBeforeAmount1) == 0){
				return jsonResult = new JsonResult(false,"最后区间的上个区间结束金额已为最大值");
			}
			BigDecimal endBeforeAmount2 = new BigDecimal(Integer.valueOf(endBeforeAmount) + 1);
			if(lastStartAmount1.compareTo(endBeforeAmount1) == -1){
				return jsonResult = new JsonResult(false,"最后区间开始金额必须大于上个区间的结束金额");
			}
			if(lastStartAmount1.compareTo(endBeforeAmount2) != 0){
				return jsonResult = new JsonResult(false,"最后区间开始金额必须为上个区间的结束金额加1");
			}
			/*if(Integer.valueOf(lastStartAmount) < Integer.valueOf(endBeforeAmount)){
				return jsonResult = new JsonResult(false,"最后区间开始金额必须大于上个区间的结束金额");
			}
			if(Integer.valueOf(lastStartAmount) != (Integer.valueOf(endBeforeAmount) + 1)){
				return jsonResult = new JsonResult(false,"最后区间开始金额必须为上个区间的结束金额加1");
			}*/
			String lastEndAmount1 = null;//最后区间的结束金额
			if(StringUtil.isEmpty(lastEndAmount)){
				String num = "";
				for (int j = 0; j < 10; j++) {
					num += 9;
				}
				lastEndAmount1 = num;
			}else{
				lastEndAmount1 = lastEndAmount;
			}
			BigDecimal lastEndAmount2 = new BigDecimal(lastEndAmount1);
			if(lastStartAmount1.compareTo(lastEndAmount2) == 1){
				return jsonResult = new JsonResult(false,"最后区间开始金额不能大于结束金额");
			}
			range2.setStartAmount(lastStartAmount1);
			range2.setEndAmount(lastEndAmount2);
			if(StringUtil.isEmpty(lastRedAcount)){
				return jsonResult = new JsonResult(false,"最后区间的红包金额为空");
			}else{
				BigDecimal lastRedAcount1 = new BigDecimal(lastRedAcount);
				range2.setRedAmount(lastRedAcount1);
			}
			range2.setRuleNo(ruleNo);
			list.add(range2);
			/**********************最后区间***************************/
		}
		result = rangeDao.insertbatch(list);
		if(result > 0){
			jsonResult = new JsonResult(true,"操作成功");
		}else{
			jsonResult = new JsonResult(false,"操作失败");
		}
		return jsonResult;
	}
 	
	@Override
	public RedEnvelopeRuleVo selectRedRuleByRuleNo(String ruleNo) {
		RedEnvelopeRuleVo vo = new RedEnvelopeRuleVo();
		RedEnvelopeRule envelopeRule = envelopeRuleDao.selectRedEnvelopeRuleByRuleNo(ruleNo);
		vo.setEnvelopeRule(envelopeRule);
		List<RedRange> ranges = rangeDao.selectRedRangeByRuleNo(ruleNo);
		vo.setRange(ranges);
		return vo;
	}

	@Override
	public JsonResult updateRedEnvelopeRule(RedEnvelopeRuleVo ruleVo) {
		JsonResult jsonResult = new JsonResult(false,"操作失败");
		int result = 0;//影响行数
		if(ruleVo != null){
			RedEnvelopeRule rule = ruleVo.getEnvelopeRule();
			if(rule != null){
				//判断 有效期类型
				if("DAYS".equals(rule.getDayType())){
					rule.setValidTermType(rule.getDayType());
					rule.setValidTermDays(rule.getValidTermDays());
				}else{
					rule.setValidTermType(rule.getValidTermType());
					rule.setValidTermDays(null);
				}
				//金额为区间
				if("AREA".equals(rule.getAmtType())){
					rule.setAmount(null);
					rule.setAmountPercent(null);
					if(ruleVo.getEndAmount() == null || ruleVo.getStartAmount() == null || ruleVo.getRedAmount() == null){
						return jsonResult=new JsonResult(false,"金额为区间时，至少必须存在一个区间!");
					}
				}
				//金额为固定值
				if("FIX".equals(rule.getAmtType())){
					rule.setAmountPercent(null);
					ruleVo.setStartAmount(null);
					ruleVo.setEndAmount(null);
					ruleVo.setRedAmount(null);
				}
				//金额为比例
				if("PER".equals(rule.getAmtType())){
					rule.setAmount(null);
					ruleVo.setStartAmount(null);
					ruleVo.setEndAmount(null);
					ruleVo.setRedAmount(null);
				}
				//判断触发动作是否为投资
				if(!"INVEST".equals(rule.getTriggerAction())){
					rule.setOverAmount(null);
				}
				//更新规则
				result = envelopeRuleDao.updateByPrimaryKeySelective(rule);
				if(result > 0){
					List<RedRange> list = rangeDao.selectRedRangeByRuleNo(rule.getRuleNo());
					if(list != null){
						if(list.size() > 0){//若存在区间先删除再添加
							//删除之前相关的金额区间
							result = rangeDao.deleteRedRangeByRuleNo(rule.getRuleNo());
							if(result > 0){
								//更新相关金额区间
								if(ruleVo.getEndAmount() == null || ruleVo.getStartAmount() == null || ruleVo.getRedAmount() == null){
									jsonResult=new JsonResult(true,"更新成功!");
								}else{
									if(ruleVo.getEndAmount().length != 0 || ruleVo.getStartAmount().length != 0 || ruleVo.getRedAmount().length != 0){
										jsonResult = addRange(rule.getRuleNo(), ruleVo);
										if(jsonResult.isSuccess()){
											jsonResult=new JsonResult(true,"更新成功!");
										}
									}else{
										jsonResult=new JsonResult(true,"更新成功!");
									}
								}
							}
						}else{//若无区间直接添加
							//更新相关金额区间
							if(ruleVo.getEndAmount() == null || ruleVo.getStartAmount() == null || ruleVo.getRedAmount() == null){
								jsonResult=new JsonResult(true,"更新成功!");
							}else{
								if(ruleVo.getEndAmount().length != 0 || ruleVo.getStartAmount().length != 0 || ruleVo.getRedAmount().length != 0){
									jsonResult = addRange(rule.getRuleNo(), ruleVo);
									if(jsonResult.isSuccess()){
										jsonResult=new JsonResult(true,"更新成功!");
									}
								}else{
									jsonResult=new JsonResult(true,"更新成功!");
								}
							}
						}
					}
				}
			}
		}
		return jsonResult;
	}

	@Override
	public JsonResult updateRedRuleStatus(String ruleNo, String type) {
		JsonResult jsonResult = new JsonResult(false,"操作失败");
		RedEnvelopeRule rule = new RedEnvelopeRule();
		rule.setRuleNo(ruleNo);
		//规则信息
		RedEnvelopeRule rule2 = envelopeRuleDao.selectRedEnvelopeRuleByRuleNo(ruleNo);
		//jsp传过来的值为启用，则为已失效-INVALID
		String invalid = DictConstant.redRuleStatus.INVALID.getCode();
		//jsp传过来的值为失效，则为生效-HAD_VALID
		String hadValid = DictConstant.redRuleStatus.HAD_VALID.getCode();
		if(invalid.equalsIgnoreCase(type)){
			//规则状态--若生效时间小于等于当前日期，则为已生效；若生效日期大于当前时间，则为待生效
			Date startDate = rule2.getStartDate();//生效时间
			if(DateUtil.isAfter(startDate, new Date())){
				rule.setStatus(DictConstant.redRuleStatus.WAIT_VALID.getCode());
			}else{
				rule.setStatus(DictConstant.redRuleStatus.HAD_VALID.getCode());
			}
		}else if(hadValid.equalsIgnoreCase(type)){
			//失效将状态置为已失效
			rule.setStatus(invalid);
		}
		int result = envelopeRuleDao.updateByPrimaryKeySelective(rule);
		if(result > 0){
			jsonResult = new JsonResult(true,"操作成功");
		}
		return jsonResult;
	}

	@Override
	public JsonResult delRedRule(String ruleNo) {
		JsonResult jsonResult = new JsonResult(false,"删除失败");
		RedEnvelopeRule rule = new RedEnvelopeRule();
		rule.setRuleNo(ruleNo);
		rule.setDelFlag(DictConstant.FlagStatus.Y.toString());
		int result;
		try {
			result = envelopeRuleDao.updateByPrimaryKeySelective(rule);
			if(result > 0){
				//若存在金额区间则删除，若没有返回
				List<RedRange> list = rangeDao.selectRedRangeByRuleNo(rule.getRuleNo());
				if(list.size() > 0){
					//删除之前相关的金额区间
					result = rangeDao.deleteRedRangeByRuleNo(ruleNo);
					if(result > 0){
						jsonResult = new JsonResult(true,"删除成功");
					}
				}else{
					jsonResult = new JsonResult(true,"删除成功");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonResult;
	}

	@Override
	public PageBean<RedEnvelopeRule> selectRedRuleByConditions(Map<String, Object> paramMap) {
		assert paramMap.get(PageQuery.PAGEQUERY) != null;
		if(!StringUtil.isEmpty((String) paramMap.get("conditions"))){	
			paramMap.put("conditions", String.valueOf(paramMap.get("conditions")).trim().replaceAll("%", "\\\\%").replaceAll("_", "\\\\_"));
		}
		//开始时间-开始时间
		String startCreatTime = (String) paramMap.get("startCreatTime");
		if (StringUtils.isNotBlank(startCreatTime))
			paramMap.put("startCreatTime", startCreatTime.concat(" 00:00:00"));
		//开始时间-结束时间
		String endCreatTime = (String) paramMap.get("endCreatTime");
		if (StringUtils.isNotBlank(endCreatTime))
			paramMap.put("endCreatTime", endCreatTime.concat(" 23:59:59"));
		//生效时间-开始时间
		String startStartDate = (String) paramMap.get("startStartDate");
		if (StringUtils.isNotBlank(startStartDate))
			paramMap.put("startStartDate", startStartDate.concat(" 00:00:00"));
		//生效时间-结束时间
		String endStartDate = (String) paramMap.get("endStartDate");
		if (StringUtils.isNotBlank(endStartDate))
			paramMap.put("endStartDate", endStartDate.concat(" 23:59:59"));
		
		int totalCount = envelopeRuleDao.selectCountRuleByConditions(paramMap);
		PageBean<RedEnvelopeRule> page = new PageBean<RedEnvelopeRule>(totalCount);
		page.setPage(((PageQuery) paramMap.get(PageQuery.PAGEQUERY)).getPage());
		page.setRows(envelopeRuleDao.selectRuleByConditions(paramMap));
		return page;
	}
	
	/**
	 * 计算时间差
	 * @param createTime
	 * @param startTime
	 * @param day
	 * @return
	 */
	public boolean calculateDatePoor(Date createTime, Date startTime, int dayCount){
		boolean flag = false;
		long diff = (createTime.getTime() - startTime.getTime());
		//相差的天数
		long days = diff / (1000 * 60 * 60 * 24);
		if(days <= dayCount){
			flag = true;
		}
		return flag;
	}
	
	/**
	 * 比较两个时间大小
	 * @param createTime
	 * @param startTime
	 * @return
	 */
	public boolean checkDate(Date createTime, Date startTime){
		boolean flag = false;
		 if (createTime.getTime() <= startTime.getTime()) {
			 flag = true;//当前时间小于生效时间
		 }
		return flag;
	}
	
	/**
	 * 两个时间是否相等大小
	 * @param createTime
	 * @param startTime
	 * @return
	 */
	public boolean checkEqualDate(Date createTime, Date startTime){
		boolean flag = false;if(createTime.getTime() == startTime.getTime()){
			 flag = true;//当前时间等于生效时间
		 }
		return flag;
	}
	
}
